if(window.io == null){
    window.io = require("socket-io");
}
 
var Global = cc.Class({
    extends: cc.Component,
    statics: {
        ip:"192.168.1.100:8081",
        sio:null,
        handlers:{},
        addHandler:function(event,fn){
            if(this.handlers[event]){
                console.log("event:" + event + "' handler has been registered.");
                return;
            }

            var handler = function(data){
                //console.log(event + "(" + typeof(data) + "):" + (data? data.toString():"null"));
                if(event != "disconnect" && typeof(data) == "string"){
                    data = JSON.parse(data);
                }
                fn(data);
            };
            
            this.handlers[event] = handler; 
            if(this.sio){
                console.log("register:function " + event);
                this.sio.on(event,handler);
            }
        },
        connect:function(fnConnect,fnError) {
            var opts = {
                reconnection:false,
            }
            this.sio = window.io.connect(this.ip,opts);
            this.sio.on('reconnect',function(){
                console.log('reconnection');
            });
            this.sio.on('connect',fnConnect);
            for(var key in this.handlers){
                var value = this.handlers[key];
                if(typeof(value) == "function"){
                    console.log("register:function " + key);
                    this.sio.on(key,value);
                }
            }
        },
        send:function(event,data){
            if(data != null && (typeof(data) == "object")){
                data = JSON.stringify(data);
                //console.log(data);              
            }
            this.sio.emit(event,data);  
        },
        
        close:function(){
            this.sio.close();
            this.sio = null;
        }
        
    },
});